package com.zcn.io.common.util;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.zcn.io.common.entity.OrderMain;
import com.zcn.io.common.entity.PayDetail;
import com.zcn.io.common.vo.PayTotalVo;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * @desc:
 * @author: 202438 邱建伟
 * @date: 2024/9/25 23:28
 * @Copyright (c) 2024, 江苏金恒信息科技股份有限公司
 */
public class PayCalculateUtils {

    public static BigDecimal getBigDecimal(String value) {
        if (StrUtil.isEmpty(value)) {
            return BigDecimal.ZERO;
        }
        try {
            return new BigDecimal(value);
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }


    public static BigDecimal add(String a, String b) {
        return add(getBigDecimal(a), getBigDecimal(b));
    }

    public static BigDecimal add(BigDecimal a, BigDecimal b) {
        return a.add(b);
    }

    public static PayTotalVo getPayTotalVo(OrderMain orderMain, List<PayDetail> payDetailList) {
        if (orderMain == null) {
            throw new RuntimeException("订单信息不能为空!");
        }
        List<PayDetail> payDetails = Optional.ofNullable(payDetailList).orElse(ListUtil.empty());

        BigDecimal orderAmount = getBigDecimal(orderMain.getOrderAmount());
        BigDecimal payTotal = BigDecimal.ZERO;
        BigDecimal expenditureTotal = BigDecimal.ZERO;
        for (PayDetail payDetail : payDetails) {
            payTotal = add(payTotal, getBigDecimal(payDetail.getPayValue()));
            expenditureTotal = add(expenditureTotal, getBigDecimal(payDetail.getRebateValue()));
        }
        BigDecimal restTotal = orderAmount.subtract(payTotal);
        BigDecimal profit = payTotal.subtract(expenditureTotal);
        return new PayTotalVo(orderAmount.toString(), payTotal.toString(), expenditureTotal.toString(),
                restTotal.toString(), profit.toString());

    }

    public static String sub(String incomeTotal, String expenditureTotal) {
        return getBigDecimal(incomeTotal).subtract(getBigDecimal(expenditureTotal)).toString();
    }
}
